package com.zhfj.config;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.*;

/**
 * Created on 2017/11/30.
 *
 * @author Jie
 */
public class WebAppInitialization extends AbstractAnnotationConfigDispatcherServletInitializer {


    /**
     * IOC 环境配置
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{RootConfig.class};
    }


    /**
     * DispatcherServlet环境配置
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebConfig.class};
    }


    /**
     * 拦截请求配置
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }


    /**
     * 配置文件上传
     * @param registration
     */
    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        //上传文件的路径
        // TODO: 2017/11/30 文件上传路径未确认
        String filepath = "/Users/hi/project/IdeaProjects/EasyBlog/src/main/webapp/uploads/";
        //单文件大小5MB
        Long singleMax = (long) (5 * Math.pow(2, 20));
        //全部文件大小10MB
        Long totalMax = (long) (10 * Math.pow(2, 20));
        //设置上传文件的配置
        registration.setMultipartConfig(new MultipartConfigElement(filepath, singleMax, totalMax, 0));
    }


    /**
     * 配置编码过滤器
     * @param servletContext
     * @throws ServletException
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("characterEncodingFilter",new CharacterEncodingFilter());
        encodingFilter.setInitParameter("encoding","UTF-8");
        encodingFilter.setInitParameter("forceEncoding","true");
        encodingFilter.addMappingForUrlPatterns(null,true,"/*");
    }
}
